package com.fishbone.mybatisplus.generator;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;

import javax.annotation.Resource;

/**
 * @ClassName GeneratorRunner
 * @Author huyaxi
 * @DATE 2020/4/26 10:55
 */
public class GeneratorRunner implements ApplicationRunner {

    @Resource
    private MybatisPlusGeneratorProperties generatorProperties;
    @Resource
    private DataSourceProperties dataSourceProperties;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if(generatorProperties.isEnabled()){
            execute();
        }
    }

    public void execute(){
        AutoGenerator generator = new AutoGenerator();
        String path = this.getClass().getResource("/").getPath();
        // 设置全局配置
        GlobalConfig globalConfig = generatorProperties.getGlobalConfig();
        globalConfig.setOutputDir(path.substring(0,path.length()-16)+"/src/main/java");
        generator.setGlobalConfig(globalConfig);
        // 设置数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName(dataSourceProperties.getDriverClassName());
        dataSourceConfig.setUsername(dataSourceProperties.getUsername());
        dataSourceConfig.setPassword(dataSourceProperties.getPassword());
        dataSourceConfig.setUrl(dataSourceProperties.getUrl());
        generator.setDataSource(dataSourceConfig);
        // 设置包配置
        generator.setPackageInfo(generatorProperties.getPackageConfig());
        // 设置模板引擎配置
        generator.setTemplate(new TemplateConfig());
        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(true);
        generator.setStrategy(strategyConfig);
        // 开始执行
        generator.execute();
    }
}
